#!-*- encoding:utf8 -*-
from django.template import Template, Context, RequestContext
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.contrib.auth.models import User

from newosmp.report.models import Report, ReportReceive
from newosmp.monitor.models import Monitor
from newosmp.users.models import UserProfile
from newosmp.host.models import Host, Product
from newosmp.util import commom
from newosmp.host.models import Host
from newosmp.strategy.models import Tpl
from newosmp.group.models import Group
from newosmp.define import *

from django.db.models import Q

from time import sleep
import time, math, hashlib

def index(request):
    lst = Report.objects.all()
    return render_to_response("report.html", locals())


def add(request):
    if request.method == 'POST':
        name = request.POST.get('name', '')
        table =  "report_" + hashlib.md5(name.encode('utf-8')).hexdigest()[:16]
        #新增插入操作 - 先存主表
        host = ','.join(request.POST.getlist('host'))
        r = Report.objects.create(
            name=name,
            tpl =request.POST.get('tpl', ''),
            statistics=request.POST.get('statistics', ''),
            pid=Product.objects.get(id=request.POST.get('pid', '')),
            freq= int(request.POST.get('freq', 1)),
            status= True,
            filed=request.POST.get('filed', ''),
            mid = ','.join(request.POST.getlist('mid')),
            table = table,)
        r.save()
        #create report data table
        commom.createReportTable(table, request.POST.getlist('mid'), 
                                request.POST.get('statistics', ''))

        # - 再存ReportReceive表
        group = int(request.POST.get('group'))
        print group
        rr = ReportReceive.objects.create(type=0, rid =r, gid= Group.objects.get(id= group))
        rr.save()
        user = request.POST.getlist('user')
        for u in user:
            rr = ReportReceive.objects.create(type=1, rid= r, uid=User.objects.get(id=u))
            rr.save()
        return HttpResponseRedirect("/report/")
    else:
        tpl = TPL_ITEMS.keys()
        group = Group.objects.all()
        user = User.objects.all()
        product = Product.objects.filter(has_host = 'T')
        statistics = CH_STAT
        return render_to_response("reportadd.html", locals())


def edit(request):
    if request.method == 'POST':
        #修改 首先清除子表
        id = request.POST.get('id')
        r = Report.objects.get(id = int(id))
        rr = ReportReceive.objects.filter(rid = r)
        rr.delete()
        #修改Report
        r.name=request.POST.get('name', '')
        r.tpl=request.POST.get('tpl', '')
        r.statistics=request.POST.get('statistics', '')
        r.freq= int(request.POST.get('freq', 1))
        r.filed=request.POST.get('filed', '')
        r.mid = ','.join(request.POST.getlist('mid'))
        r.pid = Product.objects.get(id=request.POST.get('pid', ''))
        r.save()

        # - 再存ReportReceive表
        group = int(request.POST.get('group'))
        print group
        rr = ReportReceive.objects.create(type=0, rid =r, gid= Group.objects.get(id= group))
        rr.save()
        user = request.POST.getlist('user')
        for u in user:
            rr = ReportReceive.objects.create(type=1, rid= r, uid=User.objects.get(id=u))
            rr.save()
        return HttpResponseRedirect("/report/")

    else:
        id = request.GET.get('id')
        report = Report.objects.get(id = int(id))
        tpl = TPL_ITEMS.keys()
        group = Group.objects.all()
        user = User.objects.all()
        product = Product.objects.filter(has_host = 'T')
        statistics = CH_STAT
        return render_to_response("reportedit.html",locals())


def delete(request):
    r = Report.objects.get(id= int(request.GET.get("id")))
    r.delete()
    return HttpResponseRedirect("/report")

def detail(request):
    id = request.GET.get('id')
    report = Report.objects.get(id = int(id))
    table = report.table
    mids = report.mid.split(',')
    monitor = Monitor.objects.filter(id__in = mids)
    lst = []
    for m in monitor:
        lst.append("%s|%s" % (m.id, m.name))
    items = ":".join(lst)
    return render_to_response("reportdetail.html", locals())

def search(request):
    if request.method == 'POST':
        key = request.POST.get('key', '')#报表名称 报表类型 
    else:
        key = request.GET.get('key', '')#报表名称 报表类型
    if key:
        q = Q(name__contains = key)|Q(tpl = key)
        lst = Report.objects.filter(q).order_by('-id')
    return render_to_response("report.html",locals())


def ajax_get_tpl(request):
    tpl = request.GET.get('tpl')
    items = TPL_ITEMS[tpl]
    return render_to_response("report-tpl-items.html", locals())

def ajax_get_monitor(request):
    tpl = request.GET.get('tpl')
    pid = request.GET.get('pid')
    monitors = Monitor.objects.filter(pid = pid, tpl=tpl)
    return render_to_response("report-tpl-monitor.html", locals())


def reportinfo(request, id):
    return HttpResponse("monitor project info!!")

def pausereport(request, id):
    return HttpResponse("stop!")

def timecontrol(request):
#    commom.sendmail("yilan_report@baofeng.com","zcq.0@163.com","标题：","内容：")
    while True:
        mailreport()
        sleep(100)

def mailreport(request):
    rr = ReportReceive.objects.all()
    for r in rr:
#        print "%s,%s,%s,%s,%s"%(r.id,r.rid,r.uid.id,r.freq,r.sendtime)
        id = r.id
        user = User.objects.get(id=r.uid.id)
        re = Report.objects.get(id=r.rid.id)
        mid = re.mid.id
        freq = r.freq
        #if not r.sendtime:
        #   r.sendtime = 0
        #sendtime = r.sendtime
        #t = int(time.time()*1000) - int(sendtime)
        t = int(t / 1000)
        creatmail(id, 1, mid, freq, user.email)
        print "+++++++++++++++"
    print "---------------"

def creatmail(id, t, mid, freq, mail):
    result = ""
    day = 86400
    week = 604800
    month = 2592000
    #根据时差确定是否发送邮件及发送邮件的方式和内容
    if freq == 0:
        if t >= day:
            content = getcontent(freq, mid)
            result = commom.sendmail(mail, "OSMP: Daily Report", content)
    if freq == 1:
        if t >= week:
            content = getcontent(freq, mid)
            result = commom.sendmail(mail, "OSMP: Weekly Report", content)
    if freq == 2:
        if t >= month:
            content = getcontent(freq, mid)
            result = commom.sendmail(mail, "OSMP: Monthly Report", content)
    if result == "success":
        ReportReceive.objects.filter(id=id).update(sendtime=int(time.time()*1000))



